package com.wuliupai.delivery.wuliupaidelivery.activity;

import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.TextView;


import com.wuliupai.delivery.wuliupaidelivery.App;
import com.wuliupai.delivery.wuliupaidelivery.R;
import com.wuliupai.delivery.wuliupaidelivery.bean.BankCardRegexEntity;
import com.wuliupai.delivery.wuliupaidelivery.bean.WalletEntity;
import com.wuliupai.delivery.wuliupaidelivery.net.NetResultOperate;
import com.wuliupai.delivery.wuliupaidelivery.ui.ContentWithSpaceEditText;
import com.wuliupai.delivery.wuliupaidelivery.utils.JsonUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.SharePreferenceUtil;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 添加银行卡界面
 */
@EActivity(R.layout.activity_wallet_add_bank_card)
public class WalletAddBankCard extends AppBaseActivity {

    private String bankNamePosition;//发卡银行
    private String bank;//上传银行卡数据
    private String aesUpload;//加密上传银行卡数据
    BankCardRegexEntity bankCardRegexEntity;//银行卡效验数据
    private String bankName;//通过正则判定的发卡银行

    @Bean(SharePreferenceUtil.class)
    SharePreferenceUtil sharePreferenceUtil;
    @Extra("pagerTitle")
    int pagerTitle;//  添加银行卡(0) 修改银行卡(1)
    @Extra("bankCardNum")
    String bankCardNum = "";//银行卡号
    String bankCandName = "";//持卡人名

    @ViewById(R.id.et_wallet_bank_card_num)//银行卡号
            ContentWithSpaceEditText et_wallet_bank_card_num;

    @ViewById(R.id.et_wallet_bank_card_Cardholder)//持卡人
            TextView et_wallet_bank_card_Cardholder;

    @ViewById(R.id.tv_addHairpinBank)//显示发卡银行
            TextView tv_addHairpinBank;

    @ViewById(R.id.btn_My_Wallet_bank_card_add)
    TextView btn_My_Wallet_bank_card_add; // 添加或修改银行卡按钮

    @Click(R.id.btn_My_Wallet_bank_card_add)
        //点击添加银行卡 上传数据
    void addBankCardOnClick() {
        //获取发卡银行
        if (bankNamePosition == null || "".equals(bankNamePosition) || "-1".equals(bankNamePosition)) {
            App.toast("暂不支持当前银行");
        } else {
            bank = bankNamePosition;
        }

        String bankCardCardholder = et_wallet_bank_card_Cardholder.getText().toString().trim();

        //对数据进行见状性判断
        if (et_wallet_bank_card_num.checkTextRight()) {
            if (!TextUtils.isEmpty(bank)) {
                if (!TextUtils.isEmpty(bankCardCardholder)) {

                    String bankCardNum = et_wallet_bank_card_num.getText().toString().trim().replaceAll("\\s*", "");
                    //LoadingDialog
                    uploadBankCard(bankCardNum, bankCardCardholder, bank);
                } else {
                    //当持卡人数据为空时
                    App.toast("持卡人不能为空，请输入正确的持卡人");
                }
            } else {
                //当发卡银行数据为空时
                Log.i("wuliupai", "WalletAddBankCard: " + "发卡银行不能为空，请选择发卡银行");
                //WuliupaiApplication.toast("发卡银行不能为空，请选择发卡银行");
            }
        }
    }

    /**
     * 初始化界面
     */
    @AfterViews
    void startPage() {
        //设置界面 title
        if (pagerTitle == 0) { // 添加银行卡
            setDefaultTitle(this, R.string.strings_my_info_wallet_my_add_bank_card);
            btn_My_Wallet_bank_card_add.setText(R.string.strings_my_info_wallet_my_add_bank_card);
        } else if (pagerTitle == 1) {//修改银行卡
            setDefaultTitle(this, R.string.strings_my_wallet_amend_bandCard);
            btn_My_Wallet_bank_card_add.setText(R.string.strings_my_wallet_amend);
        }

        bankCandName = sharePreferenceUtil.getMyInfo(this).getName();

        //读取Bankcard文件 判断发卡银行
        try {
            InputStream is = getResources().getAssets().open("Bankcard");

            int size = is.available();

            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();

            //解析发卡银行json数据
            String BankcardRegexJson = new String(buffer, "UTF-8");
            bankCardRegexEntity = (BankCardRegexEntity) JsonUtils.parseJsonString(BankcardRegexJson, BankCardRegexEntity.class);

        } catch (IOException e) {
            e.printStackTrace();
        }

        //对输入的银行卡号进行监听
        et_wallet_bank_card_num.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            //对银行卡号进行判断
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                parserBankCard(s);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        //设置跳转的银行卡号数据
        if (bankCardNum != "" || bankCardNum != null) {
            et_wallet_bank_card_num.setText(bankCardNum);
            parserBankCard(bankCardNum);
        }

        //设置跳转的持卡人名称
        if (bankCandName != "" || bankCardNum != null) {
            et_wallet_bank_card_Cardholder.setText(bankCandName);
        }
    }

    /**
     * 判断当前银行类型
     */
    private void parserBankCard(CharSequence s) {
        int count = 0;
        if (10 < s.length()) {
            String str = s.toString();
            str = str.replaceAll("\\s*", "");

            List<BankCardRegexEntity.InfoBean> infos = bankCardRegexEntity.getInfo();
            for (BankCardRegexEntity.InfoBean info : infos) {
                String regex = info.getRegex();

                //对银行卡号进行正则判定 发卡银行
                boolean matches = str.matches(regex);
                if (matches) {
                    //通过判断银行卡号 获取发卡银行
                    bankName = info.getBankName();
                    tv_addHairpinBank.setText(bankName);
                    //返回当前发卡银行对应的数值
                    bankNamePosition = bankPosition(bankName) + "";
                    //当符合正则 计数器加一
                    count += 1;
                }
            }
            //当循环完毕计数器为0时 判定没有当前卡号的发卡银行
            if (count == 0) {
                tv_addHairpinBank.setText("");
                //返回当前发卡银行对应的数值
                bankNamePosition = null;
            }
        }
    }

    /**
     * 上传添加银行卡数据
     */
    private void uploadBankCard(String card, String name, String bank) {

        WalletEntity uploadBankCard = new WalletEntity(card, name, bank);
        String jsonUpload = JsonUtils.createJsonString(uploadBankCard);
        Log.i("wuliupai", "发送上传银行卡数据------" + jsonUpload);
        try {
            aesUpload = JsonUtils.aes(jsonUpload);
            callNet(this, "submituserbankinfo", aesUpload, new NetResultOperate() {
                @Override
                public void onSuccess(String content) {
                    if (pagerTitle == 0) {
                        //添加银行卡成功
                        sharePreferenceUtil.setWhetherBank(1);
                        App.toast("银行卡添加成功");
                    } else if (pagerTitle == 1) {
                        //修改银行卡成功
                        App.toast("银行卡修改成功");
                    }
                    finish();
                }

                @Override
                public void onDataEmpty(String content) {
                }

                @Override
                public void onDataEnd(String content) {
                }

                @Override
                public void onErr(String errorCode, String errorMsg, Context mContext) {
                    super.onErr(errorCode, errorMsg, mContext);
                    if (pagerTitle == 0) {
                        if (errorCode.equals(NetResultOperate.WITHDRAWAL_FAILURE_CURRENT_CARD_CANNOT_CHANGED)){
                            App.toast(errorMsg);
                        }else {
                            App.toast("银行卡添加失败");
                        }
                    } else if (pagerTitle == 1) {
                        if (errorCode.equals(NetResultOperate.WITHDRAWAL_FAILURE_CURRENT_CARD_CANNOT_CHANGED)){
                            App.toast(errorMsg);
                        }else {
                            App.toast("银行卡修改失败");
                        }
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回当前发卡银行对应的数值 不支持当前银行返回-1
     */
    private int bankPosition(String bankName) {

        String[] bankTitle = getResources().getStringArray(R.array.BankCardName);
        for (int i = 0; i < bankTitle.length; i++) {
            if (bankTitle[i].equals(bankName)) {
                return i + 1;
            }
        }
        return -1;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}

